<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of soaUsers
 *
 * @author dxx
 */

namespace app\common\model\jooj_member;

use think\Model;

class MemberIndexInfo extends Model {

    protected $base_table = 'jj_member_index_info';
    protected $connection = ['database' => 'jooj_member'];

    /**
     * 构造方法，用于判断表是否存在，如果不存在就创建
     * @param type $company_id
     */
    public function __construct($company_id = []) {

        if (!is_array($company_id)) {
            $this->table = $this->base_table . '_' . $company_id;
        }
        parent::__construct($company_id);
    }

    /**
     * 添加一个信息会粉信息
     * @param type $params
     * @param type $memberCode
     * @return boolean
     */
    public function addMemberInfo($params = [], $memberCode = '') {

        $IndexInfoData['member_code'] = $memberCode;
        $IndexInfoData['service_p'] = isset($params['service_p']) ? $params['service_p'] : null;
        $IndexInfoData['service_store'] = isset($params['service_store']) ? $params['service_store'] : null;
        $IndexInfoData['service_qrscene'] = isset($params['service_qrscene']) ? $params['service_qrscene'] : null;

        $IndexInfoData['first_p'] = $IndexInfoData['service_p'];
        $IndexInfoData['first_store'] = $IndexInfoData['service_store'];
        $IndexInfoData['first_qrscene'] = $IndexInfoData['service_qrscene'];
        $IndexInfoData['last_ts'] = time();

        $IndexInfoData = array_filter($IndexInfoData);
        $res = $this->setTable($this->table)->insert($IndexInfoData);
        if ($res === false) {
            return false;
        }
        return true;
    }

    /**
     * 更新表字段
     * @param type $field
     * @param type $value
     * @param type $memberCodeArr
     * 
     * 此方法主要去更改，service_p,service_store，service_qrscene 以及对应的
     * first数据的判定+修改
     */
    public function updateValue($field, $value, $memberCodeArr) {

        if (empty($value)) {
            return true;
        }

        $memberCodeString = implode(',', $memberCodeArr);
        $where = "member_code in ($memberCodeString) and $field <> '' and $field <> '0' and $field is not null";

        //1、更新当前字段
        $single = $this->setTable($this->table)->where($where)->field('member_code')->find();
        $memberCode = isset($single['member_code']) ? $single['member_code'] : '';

        if (empty($memberCode)) {
            $memberCode = reset($memberCodeArr);
        }
        $this->setTable($this->table)->where(['member_code' => $memberCode])->update(["{$field}" => $value, 'last_ts' => time()]);

        switch ($field) {
            case 'service_p':
                //2、查看有没有first_p
                $andWhere = "member_code in ($memberCodeString) and first_p <> '' and first_p <> '0' and first_p is not null";
                $res = $this->setTable($this->table)->where($andWhere)->find();
                if (empty($res)) {
                    //没找到一条，那么基于这种情况就需要更新first_p的数据
                    //因为随便更新到一条上去，所以就以service_p的这个数据的memberCode为准更新即可
                    $this->setTable($this->table)->where(['member_code' => $memberCode])->update(["first_p" => $value, 'last_ts' => time()]);
                }
                break;
            case 'service_store':
                //2、查看有没有service_store
                $andWhere = "member_code in ($memberCodeString) and first_store <> '' and first_store <> '0' and first_store is not null";
                $res = $this->setTable($this->table)->where($andWhere)->find();
                if (empty($res)) {
                    //没找到一条，那么基于这种情况就需要更新first_store的数据
                    //因为随便更新到一条上去，所以就以service_store的这个数据的memberCode为准更新即可
                    $this->setTable($this->table)->where(['member_code' => $memberCode])->update(["first_store" => $value, 'last_ts' => time()]);
                }
                break;
            case 'service_qrscene':
                //2、查看有没有service_qrscene
                $andWhere = "member_code in ($memberCodeString) and first_qrscene <> '' and first_qrscene <> '0' and first_qrscene is not null";
                $res = $this->setTable($this->table)->where($andWhere)->find();
                if (empty($res)) {
                    //没找到一条，那么基于这种情况就需要更新first_qrscene的数据
                    //因为随便更新到一条上去，所以就以service_qrscene的这个数据的memberCode为准更新即可
                    $this->setTable($this->table)->where(['member_code' => $memberCode])->update(["first_qrscene" => $value, 'last_ts' => time()]);
                }
                break;
            default :
                break;
        }

        return true;
    }

    /*
     * 更新indexInfo
     */

    public function updateIndexInfo($params) {
        $where['member_code'] = $params['member_code'];
        $data['service_p'] = $params['first_p'];
        $data['service_store'] = $params['first_store'];
        $data['last_ts'] = time();
        ($params['card_no']) ? $data['cardno'] = $params['card_no'] : '';
        ($params['card_level']) ? $data['card_lev'] = $params['card_level'] : '';
        return $this->where($where)->update($data);
    }

    /**
     * 增加indexInfo信息
     * @return type
     * @deprecated new member by leo.xie
     */
    public function addMemberIndexInfo($params) {
        $data['member_code'] = $params['member_code'];
        $data['first_p'] = $params['firstP'];
        $data['first_store'] = $params['firstStore'];
        $data['last_ts'] = time();
        return $this->insertGetId($data);
    }

    /**
     * 清理member_index_info的数据
     * 本方法的四次更新，可以合并为2次更新
     * 但修改逻辑会丢失原子性，故不做合并
     */
    public function clearBindData($memberCodeArr) {

        //保证数据完整性
        if (!is_array($memberCodeArr) || empty($memberCodeArr)) {
            return true;
        }

        //为了保证获取到first相关数据，所以时间正序
        $all_data = $this->where(['member_code' => ['in', $memberCodeArr]])->order('last_ts asc')->select();

        //要找到的first数据
        $search = [];
        $search['first_qrscene'] = null;
        $search['first_store'] = null;
        $search['first_p'] = null;

        foreach ($all_data as $item) {
            $search = $this->_getHaveIn($search, $item);
        }

        $data = [];
        $data['first_qrscene'] = null;
        $data['first_store'] = null;
        $data['first_p'] = null;
        //清空所有的数据
        $this->where(['member_code' => ['in', $memberCodeArr]])->update($data);
        $this->where(['member_code' => $memberCodeArr[0]])->update($search);


        //为了保证获取到最新的service相关数据，所以时间倒叙
        $all_data = $this->where(['member_code' => ['in', $memberCodeArr]])->order('last_ts desc')->select();

        $search = [];
        $search['service_p'] = null;
        $search['service_store'] = null;
        $search['service_qrscene'] = null;
        foreach ($all_data as $item) {
            $search = $this->_getHaveIn($search, $item);
        }
        $data = [];
        $data['service_p'] = null;
        $data['service_store'] = null;
        $data['service_qrscene'] = null;
        //清空所有的数据
        $this->where(['member_code' => ['in', $memberCodeArr]])->update($data);
        $this->where(['member_code' => $memberCodeArr[0]])->update($search);

        return true;
    }

    /**
     * 判断有没有数据
     */
    private function _getHaveIn($search, $item) {

        foreach ($search as $key => &$search_item) {
            //查找到第一个值情况下
            if (empty($search_item) && $item[$key]) {
                $search_item = $item[$key];
            }
        }

        return $search;
    }

    public function getMemberInfoData($where, $field = '*') {
        return $this->where($where)->column($field);
    }

}
